#pragma once

#include "types.h"
#include "logger.h"
#include <atomic>
#include <vector>


OPEN_JLIB_NS

class Obj {
public:
  inline Obj () noexcept {
#ifndef NDEBUG
    ++__objectCount;
#endif
  }

  virtual ~Obj () {
#ifndef NDEBUG
    --__objectCount;
#endif
  }

  inline u64 refs () const noexcept {
    return _referenceCount;
  }

  inline void retain () noexcept {
    ++_referenceCount;
  }

  inline void release () {
    debug_assert(_referenceCount > 0);
    if (--_referenceCount == 0)
      delete this;
  }

  void autorelease () noexcept;

  inline static u64 objectCount () noexcept {
#ifndef NDEBUG
    return __objectCount;
#else
    return 0UL;
#endif
  }

private:
  std::atomic<u64> _referenceCount {1};
#ifndef NDEBUG
  static std::atomic<u64> __objectCount;
#endif

  template<typename T> friend class Ptr;
};


CLOSE_JLIB_NS
